package io.github.talelin.latticy.extension.file;

import com.aliyun.oss.*;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.qiniu.common.QiniuException;
import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.latticy.module.file.AbstractUploader;
import io.github.talelin.latticy.module.file.FileConstant;
import io.github.talelin.latticy.module.file.FileProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 文件上传服务实现，上传到七牛
 *
 * @author pedro@TaleLin
 */
@Component
@Slf4j
public class AliyunOSSUploader extends AbstractUploader {

    @Autowired
    private FileProperties fileProperties;

    @Value("${lin.file.aliyunOSS.access-key-id}")
    private String accessKeyId;

    @Value("${lin.file.aliyunOSS.access-key-secret}")
    private String accessKeySecret;

    @Value("${lin.file.aliyunOSS.bucket}")
    private String bucket;

    @Value("${lin.file.aliyunOSS.endpoint}")
    private String endpoint;

    @Value("${lin.file.aliyunOSS.key}")
    private String key;

    private OSS ossClient;

    private String fileDir;

    /**
     * 因为需要得到 spring-boot 提供的配置，所以不能在 constructor 中初始化
     * 使用 PostConstruct 来初始化
     */
    @PostConstruct
    public void initUploadManager() {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        this.fileDir = "blooms/" + dateFormat.format(date) + '/';
    }

    @Override
    protected FileProperties getFileProperties() {
        return fileProperties;
    }

    @Override
    protected String getStorePath(String newFilename) {
        return key + fileDir + newFilename;
    }

    @Override
    protected String getFileType() {
        return FileConstant.REMOTE;
    }

    /**
     * 处理一个文件数据
     *
     * @param bytes       文件数据，比特流
     * @param newFilename 新文件名称
     * @return 处理是否成功，如果出现异常则返回 false，避免把失败的写入数据库
     */
    @Override
    protected boolean handleOneFile(byte[] bytes, String newFilename) {
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String objectName = fileDir + newFilename;
            //上传文件
            ossClient.putObject(bucket, objectName, byteInputStream);

            ossClient.shutdown();
        } catch (OSSException e) {
            log.error("aliyunOSS upload file OSSException error: {}", e.getMessage());
            throw new ForbiddenException(e.getMessage());
        } catch (ClientException e) {
            log.error("aliyunOSS upload file ClientException error: {}", e.getMessage());
            throw new ForbiddenException(e.getMessage());
        }
        return true;
    }


}
